﻿using System.Net.Mail;
using System.Threading;
using System;
using System.Data;
using System.IO;

namespace LoadTestingEmailRepoter.PulgIn
{
    public class LoadTestReport
    {
        public static string BuildReport(DataSet results)
        {
            Utilities hu = new Utilities();

            hu.AppendHeader("Load Test Report");
            hu.AppendSubHeader("Completed by:" + System.DateTime.Now.ToString());

            hu.AppendBlankRow();

            hu.AppendSubHeader(TableNames.SystemInfo);
            hu.FormatToRowInColonSeparatedText("Processor", Utilities.GetSystemInfo("Win32_Processor", "Caption"));
            hu.FormatToRowInColonSeparatedText("Operating System", Utilities.GetSystemInfo("Win32_OperatingSystem", "Caption"));

            hu.AppendBlankRow();

            hu.AppendSubHeader(TableNames.NetworkMix);
            hu.AppendPara(Utilities.ConvertDataTableToHtmlTable(results.Tables[TableNames.NetworkMix]));

            hu.AppendSubHeader(TableNames.BrowserMix);
            hu.AppendPara(Utilities.ConvertDataTableToHtmlTable(results.Tables[TableNames.BrowserMix]));

            hu.AppendSubHeader(TableNames.TestCounters);
            hu.AppendPara(Utilities.ConvertDataTableToHtmlTable(results.Tables[TableNames.TestCounters]));

            return hu.FormattedHtmlText;

        }

        public static void SendReport()
        {
            if (!AppReader.EmailReporterDisabled)
            {
                try
                {

                    Thread.Sleep((int)(AppReader.TestReportDelayInSeconds * 1000));

                    //getting the result data from database
                    DataSet results = LoadTestDataAccessLayer.GetLoadTestSummery();

                    //preparing the report
                    string subject = AppReader.WebSiteName + " Load Test Report";
                    string body = string.Empty;
                    body += BuildReport(results);

                    //saving the report in local directory
                    if (!string.IsNullOrEmpty(AppReader.LocalReportDirectory))
                        Utilities.WriteToFile(AppReader.LocalReportDirectory, body);

                    //export to excel
                    MemoryStream excelInMemoryReport = null;
                    if (AppReader.AttachExcelReport)
                        excelInMemoryReport = Export.ExportToMemory(results.Tables[TableNames.TestCounters]);


                    //sending the email report
                    Emailer.SendMail(subject, body, excelInMemoryReport);
                }

                catch (SmtpException ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
                catch (Exception ex2)
                {
                    System.Windows.Forms.MessageBox.Show(ex2.ToString());
                }
            }
        }
    }
}